/**
 * Copyright (c) 2012, SHX Studio.
 * All rights reserved.
 * rosary226@gmail.com
 * 
 * @author shenqianfeng
 * @date 2012-9-1  
 * @version 1.0   
 */

package com.xxx.sqfengine.primitives;

import java.nio.FloatBuffer;
import java.nio.ShortBuffer;

import javax.microedition.khronos.opengles.GL10;

import com.xxx.sqfengine.SQFGL3DObject;
import com.xxx.sqfengine.util.SQFGLBufferUtil;
import com.xxx.sqfengine.util.SQFGLCompareUtil;
import com.xxx.sqfengine.util.SQFGLConstants;


/*   
 *  rectangle vertex indices like below
 *   0
 *   --------- 3
 *   |       |
 *   |       |
 *   |       |
 *   ---------  2
 *   1     
 */
public class SQFGLRectangle extends SQFGL3DObject{

	private SQFGLVertex mLeftTop;
	private SQFGLVertex mLeftBottom;
	private SQFGLVertex mRightBottom;
	private SQFGLVertex mRightTop;
	private ShortBuffer mIndexBuf;
	private FloatBuffer mColorBuf;
	
	public SQFGLRectangle(SQFGLVertex leftTop, SQFGLVertex leftBottom, SQFGLVertex rightBottom, SQFGLVertex rightTop) {
		if(mLeftTop == null) {
			mLeftTop = leftTop;
		}
		if(mLeftBottom == null) {
			mLeftBottom = leftBottom;
		}
		if(mRightBottom == null) {
			mRightBottom = rightBottom;
		}
		if(mRightTop == null) {
			mRightTop = rightTop;
		}
		
		short indices[] = {0, 1, 2, 0, 2, 3};
		mIndexBuf = SQFGLBufferUtil.toShortBuf(indices);
		mColorBuf = generateColorBuffer();
	}
	
	public FloatBuffer floatBuf() {
		float [] buf = new float[12];
		FloatBuffer fb = FloatBuffer.wrap(buf);
		fb.position(0);
		fb.put(mLeftTop.toVerticesFloatBuf());
		fb.put(mLeftBottom.toVerticesFloatBuf());
		fb.put(mRightBottom.toVerticesFloatBuf());
		fb.put(mRightTop.toVerticesFloatBuf());
		return fb;
	}
	
	@Override
	public void draw(GL10 gl) {
		beginDraw(gl);
		getTransformManager().draw(gl);
		gl.glVertexPointer(3, GL10.GL_FLOAT, 0, floatBuf());
		gl.glColorPointer(4, GL10.GL_FLOAT, 0, mColorBuf);
		gl.glDrawElements(GL10.GL_TRIANGLES, 6, GL10.GL_UNSIGNED_SHORT, mIndexBuf);
		endDraw(gl);
	}
	
	protected FloatBuffer generateColorBuffer() {
		float [] buf = new float[16];
		FloatBuffer fb = FloatBuffer.wrap(buf);
		fb.position(0);
		fb.put(mLeftTop.getColor().toFloatBuffer());
		fb.put(mLeftBottom.getColor().toFloatBuffer());
		fb.put(mRightBottom.getColor().toFloatBuffer());
		fb.put(mRightTop.getColor().toFloatBuffer());
		return fb;
	}
}
